<?php
namespace app\common\business;

use app\common\model\mysql\Order as orderModel;
use think\facade\Cache;
class Order extends BusiBase{
	public $model = null;
	public function __construct(){
		$this->model = new orderModel();
	}

	//提交订单处理
	public function save($data){
		//生成全局唯一性订单号
		$snowflake = new \app\common\lib\Snowflake;
		$orderId = $snowflake->getInstance()->nextId();

		//获取购物车数据
		$cartObj = new Cart();
		$result = $cartObj->lists($data['user_id'],$data['ids']);

		if(!$result){
			return false;
		}
		//dump($result);
		//订单的总价格
		$price = array_sum(array_column($result, 'total_price'));
		//组装插入order表数据
		$orderData = [
			'user_id'=>$data['user_id'],
			'order_id'=>$orderId,
			'total_price'=>$price,
			'address_id'=>$data['address_id'],
		];
		//组装插入order_goods表数据
		$orderGoodsData = array_map(function($v) use ($orderId){
			$v['sku_id'] = $v['id'];
			unset($v['id']);
			$v['order_id'] = $orderId;
			return $v;
		}, $result);
		//dump($orderGoodsData);//exit;
		//开启事务
		$this->model->startTrans();
		try{
			//插入order表
			$id = $this->add($orderData);
			//dump($id);exit;
			if(!$id){
				return 0;
			}
			//插入order_goods表
			$res = (new OrderGoods())->saveAll($orderGoodsData);
			if(!$res){
				return 0;
			}
			//goods_sku更新库存
			$skuRes = (new GoodsSku())->updateStock($result);
			//goods更新库存

			//删除购物车里商品
			$cartObj->deleteRedis($data['user_id'],$data['ids']);
			$this->model->commit();
			//延迟队列
			try{
				//redis有序集合 添加 (塞入延时队列)
				Cache::zAdd(
					config('redis.order_status_key'),
					time()+config('redis.order_expire'),
					$orderId
				);
			}catch(\Exception $e){
				echo $e->getMessage();exit;
			}

			return ['id' => $orderId];
		}catch(\Exception $e){
			$this->model->rollback();
			//echo $e->getMessage();exit;
			return false;
		}
		

	}

	//订单详情
	public function detail($data){
		//条件
		$condition = [
			'user_id' => $data['user_id'],
			'order_id' => $data['order_id'],
		];
		try{
			//根据订单ID等条件获取订单表mall_order数据
			$orders = $this->model->getByCondition($condition);

		}catch(\Exception $e){
			$orders = [];
		}
		if(!$orders){
			return [];
		}

		$orders = $orders->toArray();
		//dump($orders);
		$orders = !empty($orders) ? $orders[0] : [];
		if(empty($orders)){
			return [];
		}
		$orders['id'] = $orders['order_id'];
		$orders['price'] = $orders['total_price'];
		$orders['consignee_info'] = '河南省 上蔡县 韩寨镇 任集村6号 fresh收 1500xxx';
		$orders['mall_title'] = 'abc';
		//dump($orders);//exit;

		//根据order_id获取mall_order_goods表中数据
		$orderGoods = (new OrderGoods())->getByOrderId($data['order_id']);
		//dump($orderGoods);exit;
		$orders['malls'] = $orderGoods;

		return $orders;
	}

	//处理延迟队列中超过规定时间的未付款订单
	public function checkOrderStatus(){
		//返回指定分数范围的成员
		$result = Cache::store('redis')->zRangeByScore('order_status',0,time());
		//print_r($result);exit;
		if(empty($result) || empty($result[0])){
			return false; 
		}
		
		try{
			//删除成员(从消息队列中移除该成员)
			$delRedis = Cache::store('redis')->zRem('order_status',$result[0]);
		}catch(\Exception $e){
			echo $e->getMessage();exit;
			$delRedis = '';
		}
		if($delRedis){
			echo "订单ID:{$result[0]}在规定时间内没有完成支付，被判定为过期订单 已删除!".PHP_EOL;
			/*
			1.根据订单id,查询订单表order数据，看下当前状态是否是待支付:status=1,如果是，需要把状态更新为 已取消status=7，否则不用处理

			2.第一步status=7修改之后，需要查询order_goods表，获取sku_id,num,修改goods_sku表中的库存(添加)，goods表中的库存也需要修改
			*/
		}
	}

	//根据订单ID查询订单
	public function getOrderInfoById($orderId){
		//条件
		$condtion = [
			'order_id' => $orderId,
		];
		try{
			$order = $this->model->getByCondition($condtion);
		}catch(\Exception $e){
			$order = [];
		}
		//print_r($order;exit;
		if(!$order){
			return [];
		}
		return $order->toArray();
	}

	//修改订单
	public function updateOrderStatus(){
		$url = "http://www.fresh.com:8082/api/getOrder";
		$data = [];
		/*
		$data = [
			'order_id'=>'3160134495208448',
		];*/
		//初使化init方法
	   $ch = curl_init();
	   //指定URL
	   curl_setopt($ch, CURLOPT_URL, $url);
	   //设定请求后返回结果
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   //声明使用POST方式来进行发送
	   curl_setopt($ch, CURLOPT_POST, 1);
	   //发送什么数据呢
	   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	 
	   //忽略证书
	   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	   //忽略header头信息
	   curl_setopt($ch, CURLOPT_HEADER, 0);
	   //设置超时时间
	   curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	   //发送请求
	   $output = curl_exec($ch);
	   //dump($output);exit;
	   //关闭curl
	   curl_close($ch);

	   $result = json_decode($output,true);
	   //echo '<pre>';print_r($result);//exit;
	   $arr = $result['result'];

	   //echo '<pre>';print_r($arr);exit;

	   $arrOrderId = array_keys($arr);
	   //print_r($arrOrderId);exit;
	   
	   if(empty($arrOrderId) || empty($arrOrderId[0])){
			return false;
	   }

	   try{
			//删除成员
			$delRedis = Cache::store('redis')->hDel(
				'order_pay_status_appid123456abc',
				$arrOrderId[0]
			);
		}catch(\Exception $e){
			echo $e->getMessage();exit;
			$delRedis = '';
		}
	   //var_dump($delRedis);
	   
	   try{
	   	//更新mall_order表
	   	$flag = $this->model->updateByOrderId($arrOrderId[0]);
	   }catch(\Exception $e){
	   	 echo $e->getMessage();exit;
		 return false;
	   }
	   
	   if($flag && $delRedis){
			echo "订单ID:{$arrOrderId[0]}在规定时间内已完成支付!".PHP_EOL;
		}
	   //返回数据
	   //return $output;
	}

	// 消费者
	public function getSmsInfo(){
		$info = Cache::store('redis')->lpop('sms_list');
		if($info){
			echo $info.PHP_EOL;
		}
		
	}

	public function test(){
		return 'hello';
	}
}